package br.fxfc.android.daysuntil;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import br.fxfc.android.daysuntil.DBHelper.TableDaysUntil;

public class MyCursorAdapter extends SimpleCursorAdapter {

	private final LayoutInflater mInflater;

	private Context myContext;
	
	public MyCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to) {
		super(context, layout, c, from, to);
		myContext = context;
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		TextView t = (TextView) view.findViewById(R.id.textEvent);
		t.setText(cursor.getString(cursor
				.getColumnIndex(TableDaysUntil.COL_TEXT)));

		String dateInputString = cursor.getString(cursor
				.getColumnIndex(TableDaysUntil.COL_DATETIME));

		SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		SimpleDateFormat sdfOutput = new SimpleDateFormat("dd/MM/yyyy HH:mm");

		try {
			Date dateInput = sdfInput.parse(dateInputString);
			String dateOutputString = sdfOutput.format(dateInput);

			t = (TextView) view.findViewById(R.id.textDate);
			t.setText(dateOutputString);
			Date now = new Date();
			long diff;
			if (now.compareTo(dateInput) > 0) {
				diff = now.getTime() - dateInput.getTime();
			}
			else
			{
				diff = dateInput.getTime() - now.getTime();
			}
			
			long diffDays = (diff / (24 * 60 * 60 * 1000));
			int dayInteger = (int)(diff / (24 * 60 * 60 * 1000));
			long diffHours = (diff / (60 * 60 * 1000)) - dayInteger * 24;
			int hourInteger = (int)(diff / (60 * 60 * 1000));
			long diffMinutes = (diff / (60 * 1000)) - hourInteger * 60;

			String dateDiffOutput = String.valueOf(diffDays)
			+ " " + myContext.getString(R.string.days) + " "
			+ String.valueOf(diffHours)
			+ " " + myContext.getString(R.string.hours) + " "
			+ String.valueOf(diffMinutes)
			+ " " + myContext.getString(R.string.minutes);

			t = (TextView) view.findViewById(R.id.textCalculated);
			t.setText(dateDiffOutput);

		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		final View view = mInflater.inflate(R.layout.item, parent, false);
		return view;

	}

}
